package helper

import (
	"fmt"
	"strings"

	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
    
    "collecter/app/common/enum"
    "collecter/app/lang"
)

func InitConfiger() {
	// 所有允许的配置文件后缀名
	exts := map[string]struct{}{
		"go":         {},
		"ini":        {},
		"conf":       {},
		"json":       {},
		"yaml":       {},
		"yml":        {},
		"properties": {},
		"props":      {},
		"prop":       {},
		"hcl":        {},
		"dotenv":     {},
		"env":        {},
	}

	files := make([]string, 0, 0)
	dirPath := enum.CONF_DIR
	if err, val := ScanDir(dirPath, false); err != nil {
		panic(lang.CodeMessage(11) + ":" + err.Error())
	} else {
		files = val
	}
	// fmt.Printf("initcacher--file: %+v\n", files)
	vInstance := viper.New()
	for idx, filename := range files {
		if strings.Contains(filename, "example") {
			continue
		}
		fullName := dirPath + filename
		info := strings.Split(filename, ".")
		ext := GetExt(filename)
		if _, ok := exts[ext]; !ok {
			panic(lang.CodeMessage(11) + ": " + lang.CodeMessage(10007))
		}
		if ext == "go" {
			continue
		}
		basename := info[0]
		vInstance.SetConfigName(basename)
		vInstance.SetConfigFile(fullName)
		vInstance.SetConfigType(ext)
		vInstance.AddConfigPath(dirPath)

		if idx > 0 {
			if err := vInstance.MergeInConfig(); err != nil {
				panic(lang.CodeMessage(11) + ":" + err.Error())
			}
		} else {
			if err := vInstance.ReadInConfig(); err != nil {
				panic(lang.CodeMessage(11) + ":" + err.Error())
			}
		}
	}

	defaultSettings := vInstance.GetStringMap("default")
	if len(defaultSettings) > 0 {
		for idx, val := range defaultSettings {
			vInstance.SetDefault(idx, val)
		}
	}
	vInstance.WatchConfig()
	vInstance.OnConfigChange(func(e fsnotify.Event) {
		// 配置文件发生变更之后会调用的回调函数
		InitConfiger()
		fmt.Println("Config file changed:", e.Name)
	})
	Configer = vInstance
}
